package org.example.controller;

import jakarta.annotation.Resource;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.utils.JwtToken;
import org.example.utils.LoginUserResponseData;
import org.example.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: UserLoginController
 * Description:
 *
 * @Author Kotaro
 * @Create 2024/11/24 17:06
 * @Version 1.0
 */
@CrossOrigin //允许其他源访问我们的controller
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("login")//这里是所有用户登录的端口
    public R loginUser(@RequestParam String userId,
                       @RequestParam String password){
        if(userId.isEmpty() || password.isEmpty()){
            return R.empty("账号或密码不能为空！请重新输入！" , null);
        }else {
            try {
                if(userService.userLogin(userId , password)){
                    //创建token和userType
                    String token = JwtToken.createToken(userId);
                    String userType = null;
                    if(userId.startsWith("E")){
                        userType = "elderly";
                    } else if (userId.startsWith("J")) {
                        userType = "family";
                    } else if (userId.startsWith("C")) {
                        userType = "community";
                    }else {
                        userType = "volunteers";
                    }

                    LoginUserResponseData loginUserResponseData = userService.selectUserByUserId(userId);

                    loginUserResponseData.setToken(token);
                    loginUserResponseData.setUserType(userType);
                    loginUserResponseData.setUserId(userId);

                    return R.successful("登陆成功！" , loginUserResponseData);
                }else {
                    return R.error("账号或密码错误！请重新输入！" , null);
                }
            }catch (Exception e){
                return R.error("账号或密码错误！请重新输入！",null);
            }
        }
    }

    @PutMapping("insert")//这里是所有用户注册的端口
    public R insertUser(@Validated @RequestBody User user , BindingResult result){
        if(result.hasErrors()){
            return R.error("参数为null,不能修改" , null);
        }else {
            userService.insert(user);
            return R.successful("注册成功" , null);
        }

    }

}
